# 初始化角色和权限数据
from app.extensions import db
from app.models.role import Role, Permission

def init_permissions():
    """初始化权限数据"""
    permissions = [
        ('view_dashboard', '查看仪表板'),
        ('manage_users', '管理用户'),
        ('edit_content', '编辑内容'),
        ('delete_content', '删除内容'),
        ('publish_content', '发布内容'),
        ('manage_roles', '管理角色'),
        ('manage_permissions', '管理权限'),
        ('view_reports', '查看报告'),
        ('export_data', '导出数据'),
        ('import_data', '导入数据'),
        ('manage_settings', '管理设置'),
        ('view_logs', '查看日志'),
    ]
    
    for name, description in permissions:
        permission = Permission.query.filter_by(name=name).first()
        if not permission:
            permission = Permission(name=name, description=description)
            db.session.add(permission)
    
    db.session.commit()
    print("权限数据初始化完成")

def init_roles():
    """初始化角色数据"""
    # 确保权限已初始化
    init_permissions()
    
    roles = [
        ('admin', '管理员', [
            'view_dashboard', 'manage_users', 'edit_content', 'delete_content',
            'publish_content', 'manage_roles', 'manage_permissions', 'view_reports',
            'export_data', 'import_data', 'manage_settings', 'view_logs'
        ]),
        ('editor', '编辑', [
            'view_dashboard', 'edit_content', 'publish_content', 'view_reports'
        ]),
        ('author', '作者', [
            'view_dashboard', 'edit_content', 'publish_content'
        ]),
        ('viewer', '查看者', [
            'view_dashboard'
        ]),
    ]
    
    for role_name, description, permission_names in roles:
        role = Role.query.filter_by(name=role_name).first()
        if not role:
            role = Role(name=role_name, description=description)
            db.session.add(role)
            db.session.flush()  # 获取角色ID
            
            # 添加权限到角色
            for permission_name in permission_names:
                permission = Permission.query.filter_by(name=permission_name).first()
                if permission:
                    role.add_permission(permission)
    
    db.session.commit()
    print("角色数据初始化完成")

def init_roles_and_permissions():
    """初始化角色和权限数据"""
    init_roles()
    print("角色和权限数据初始化完成")

def assign_admin_role(user):
    """为用户分配管理员角色"""
    admin_role = Role.query.filter_by(name='admin').first()
    if admin_role and not user.has_role('admin'):
        user.add_role(admin_role)
        db.session.commit()
        print(f"已为用户 {user.username} 分配管理员角色")
    else:
        print(f"用户 {user.username} 已是管理员或管理员角色不存在")